<?php
/**
 * Created by lzl
 * Date: 2021 2021/8/27
 * Time: 13:56
 */
namespace App\Services\Api;
use App\Events\RegisterEvent;
use App\Exceptions\RequestException;
use App\Forms\UserForms;
use App\Models\User;
use App\Services\BaseServices as Base;
use EasyWeChat\Factory;


class AuthServices extends Base
{
    /**
     * @param $validate
     * @return array
     * @throws RequestException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public static function login($validate)
    {

        $app = Factory::miniProgram(config('wechat.mini_program.default'));
        $data = $app->auth->session($validate['code']);

        if(!isset($data['openid'])){
            throw new RequestException(json_encode($data));
        }

        $user = User::where('openid', $data['openid'])->first();

        if(blank($user)){
            //创建用户
            $create['openid'] = $data['openid'];

            //标记注册来源
            if(isset($validate['source'])){
                $create['source'] = $validate['source'];
            }

            $user = User::create($create);

            event(new RegisterEvent($user));
        }

        return $user->toArray();
    }


    /**
     * @param $validate
     * @return User|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \EasyWeChat\Kernel\Exceptions\DecryptException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public static function getUserPhone($validate)
    {
        $app = Factory::miniProgram(config('wechat.mini_program.default'));

        $session = $app->auth->session($validate['code']);

        $info = $app->encryptor->decryptData($session['session_key'], $validate['iv'], $validate['encryptedData']);

        $user = (new UserForms())->getUserDetail(UID);

        $user->update(['mobile' => $info['purePhoneNumber']]);

        return  $user->refresh();
    }
}